<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>发布订阅模式</title>
  </head>
  <body>
    <script>
      class EventEmitter {
        constructor() {
          this.subs = {}
        }
        $on(eventType, fn) {
          if (!this.subs[eventType]) {
            this.subs[eventType] = []
          }
          this.subs[eventType].push(fn)
        }
        //触发事件
        $emit(eventType) {
          if (this.subs[eventType]) {
            this.subs[eventType].forEach((handler) => {
              handler()
            })
          }
        }
      }
      //测试代码
      window.$myEmit = new EventEmitter()
      $myEmit.$on('click', () => {
        console.log('click1')
      })
      $myEmit.$on('click', () => {
        console.log('click2')
      })
      $myEmit.$emit('click')
    </script>
  </body>
</html>
